﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.Media;
using System.Diagnostics;

namespace WebQQ批量挂QQ软件
{
    public partial class frmMain : Form
    {
        string xmlPath = Application.StartupPath + @"\Config.xml";
      static  HttpListener listener;
        bool firstLoad = true;
        
        DateTime dtStart;
        Dictionary<string, string> friendList;
        public frmMain()
        {
            InitializeComponent();
            this.Text += " V" + Application.ProductVersion + " 免费版(事理)";

            //使用双缓冲，防止界面重绘时闪烁
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);// 禁止擦除背景
            SetStyle(ControlStyles.DoubleBuffer, true);// 双缓冲

            //是线程可操作控件
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            ServicePointManager.DefaultConnectionLimit = 50;//Httpwebrequest默认连接只有两个
            ServicePointManager.Expect100Continue = false;
        }
        QQData item;
        private void frmMain_Load(object sender, EventArgs e)
        {
            //添加侦听
            lin();
            dtStart = DateTime.Now;
            cboStatus.SelectedIndex = 0;
            string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);//得到桌面文件夹
            if (File.Exists(DesktopPath + "\\WebQQ3.0批量挂QQ.lnk"))
            {
                chCreateDesktopLnk.Checked = true;
            }
            Init();

            if (chkAutoLogin.Checked)
            {
                LoginSelect();
            }
       
        }

        private void Init()
        {
            
            SymmetricMethod decrypto = new SymmetricMethod();

            List<QQData> list = new List<QQData>();

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlPath);
           
            XmlNode node=doc.SelectNodes("/config/add")[0];
            item = new QQData();
            item.QQ = node.Attributes["QQ"].Value;
            item.Passwd = !string.IsNullOrEmpty(node.Attributes["Password"].Value) ? decrypto.Decrypto(node.Attributes["Password"].Value) : "";
            item.ReadyStatus = node.Attributes["Status"].Value;
            #region 加载其他选项设置

            XmlNode refreshTime = doc.SelectSingleNode("/config/Settings/add[@key='RefreshTime']");//刷新间隔
            if (refreshTime != null)
            {
                if (!string.IsNullOrEmpty(refreshTime.Attributes["value"].Value))
                    txtRefreshTime.Text = refreshTime.Attributes["value"].Value;
            }

            //是否开机启动
            string strName = Application.ExecutablePath;
            string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1, strName.LastIndexOf(".") - strName.LastIndexOf("\\") - 1);
            object obj = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", strnewName, null);
            chkRun.Checked = obj == null ? false : true;

            //自动登录所有QQ号
            XmlNode autoLogin = doc.SelectSingleNode("/config/Settings/add[@key='AutoLogin']");//自动登录
            if (autoLogin != null)
                chkAutoLogin.Checked = bool.Parse(autoLogin.Attributes["value"].Value);

        
            #endregion

            txtQQNumber.Text = item.QQ;
            txtQQPasswd.Text = item.Passwd;
           
            firstLoad = false;
        }

        //添加qq号码
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "登录")
            {
                panel2.Enabled = false;
                if (string.IsNullOrEmpty(txtQQNumber.Text.Trim()) || string.IsNullOrEmpty(txtQQPasswd.Text.Trim()))
                {
                    MessageBox.Show("QQ号码和密码不能为空！");
                    txtQQNumber.Focus();
                    return;
                }

                LoginSelect();
            }
            else
                if (btnAdd.Text == "注销")
                {
                    
                    Thread thread = new Thread(new ThreadStart(OfflineSelect));
                    thread.IsBackground = true;
                    thread.Start();
                }
        }

        //修改
        //private void btnAlter_Click(object sender, EventArgs e)
        //{
        //    if (lvMain.SelectedItems.Count > 0)
        //    {
        //        if (string.IsNullOrEmpty(txtQQPasswd.Text.Trim()))
        //        {
        //            MessageBox.Show("密码不能为空！");
        //            txtQQPasswd.Focus();
        //            return;
        //        }
        //        XmlDocument doc = new XmlDocument();
        //        doc.Load(xmlPath);
        //        XmlNode qq = doc.SelectSingleNode("/config/add[@QQ='" + txtQQNumber.Text.Trim() + "']");

        //        SymmetricMethod encrypto = new SymmetricMethod();
        //        qq.Attributes["Password"].Value = encrypto.Encrypto(txtQQPasswd.Text.Trim());

        //        qq.Attributes["Status"].Value = cboStatus.Text;

        //        doc.Save(xmlPath);
        //        QQData data = lvMain.SelectedItems[0].Tag as QQData;
        //        data.Passwd = txtQQPasswd.Text.Trim();
        //        data.ReadyStatus = cboStatus.Text;
        //        lvMain.SelectedItems[0].Tag = data;
        //        MessageBox.Show("修改成功！");
        //    }
        //    else
        //    {
        //        MessageBox.Show("请选择要修改的项！");
        //    }
        //}

        //登录所有
        //private void tsmiLoginAll_Click(object sender, EventArgs e)
        //{
        //    Thread thread = new Thread(new ThreadStart(LoginAll));
        //    thread.IsBackground = true;
        //    thread.Start();
        //}

        //private void LoginAll()
        //{
        //    lvMain.Enabled = false;
        //    try
        //    {
        //        for (int i = 0; i < lvMain.Items.Count; i++)
        //        {
        //            QQData item = lvMain.Items[i].Tag as QQData;

        //        Retry:
        //            string cookie;
        //            string verifycode = QQHelp.GetVerfyCode(item.QQ, out cookie);
        //            if (verifycode == null)//跳过这条登录
        //                continue;
        //            else
        //            {
        //                string ptwebqq, clientid, psessionid, vfwebqq;
        //                ptwebqq = clientid = psessionid = vfwebqq = string.Empty;
        //                string msg = string.Empty;
        //                bool success = QQHelp.Login(item.QQ, item.Passwd, verifycode, item.ReadyStatus, ref cookie, ref ptwebqq, ref clientid, ref psessionid, ref vfwebqq, ref msg);
        //                if (success)//登录成功
        //                {
        //                    ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
        //                    {
        //                        tssStatus2.Text = item.QQ + " 成功登录...";
        //                    }));
        //                    item.RefreshStart = DateTime.Now;
        //                    item.Status = item.ReadyStatus;
        //                    item.Cookie = cookie;
        //                    item.ClientId = clientid;
        //                    item.Ptwebqq = ptwebqq;
        //                    item.Psessionid = psessionid;
        //                    item.Vfwebqq = vfwebqq;
        //                    item.RefreshComplete = true;
        //                    lvMain.Items[i].SubItems[2].Text = item.Status;
        //                    lvMain.Items[i].SubItems[6].Text = msg;

        //                    //获取昵称
        //                    string url1 = "http://s.web2.qq.com/api/get_friend_info2?tuin=" + item.QQ + "&verifysession=&code=&vfwebqq=" + vfwebqq + "&t=" + DateTime.Now.ToFileTime();
        //                    string nickName = HttpHelp.GetHtml(url1, "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", ref cookie, Encoding.UTF8, false);
        //                    nickName = nickName.Remove(0, nickName.IndexOf("nick\":\"") + 7);
        //                    nickName = nickName.Substring(0, nickName.IndexOf("\","));
        //                    lvMain.Items[i].SubItems[1].Text = nickName;

        //                    ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
        //                    {
        //                        tssStatus2.Text = item.QQ + " 获取等级信息...";
        //                    }));

        //                    //获取等级和剩余升级天数
        //                    try
        //                    {
        //                        string level, remainDays;
        //                        string url2 = "http://s.web2.qq.com/api/get_qq_level2?tuin=" + item.QQ + "&vfwebqq=" + vfwebqq + "&t=" + DateTime.Now.ToFileTime();
        //                        string html = HttpHelp.GetHtml(url2, "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", ref cookie, Encoding.UTF8, false);
        //                        html = html.Remove(0, html.IndexOf("level\":") + 7);
        //                        level = html.Substring(0, html.IndexOf(","));
        //                        html = html.Remove(0, html.IndexOf("remainDays\":") + 12);
        //                        remainDays = html.Substring(0, html.IndexOf(","));
        //                        lvMain.Items[i].SubItems[3].Text = level;
        //                        lvMain.Items[i].SubItems[4].Text = remainDays + "天";

        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        MessageBox.Show("QQ等级信息获取失败，" + ex.Message);
        //                    }

        //                    ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
        //                    {
        //                        tssStatus2.Text = item.QQ + " 获取好友信息...";
        //                    }));

        //                    try
        //                    {
        //                        //获取好友列表
        //                        string postData = "r={\"h\":\"hello\",\"vfwebqq\":\"" + vfwebqq + "\"}";
        //                        WebHeaderCollection header;
        //                        string html2 = HttpHelp.GetHtml("http://s.web2.qq.com/api/get_user_friends2", "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", postData, ref cookie, true, out header, "application/x-www-form-urlencoded; charset=UTF-8", Encoding.UTF8, false);

        //                        friendList = new Dictionary<string, string>();//保存好友id值集合

        //                        Regex friend = new Regex("({\"flag\":)(?<flag>[0-9]{1,2}?)(,\"uin\":)(?<uin>[0-9]{5,11}?)(,\"categories\":)(?<id>[0-9]{1,2}?)(})");
        //                        foreach (Match match in friend.Matches(html2))
        //                        {
        //                            friendList.Add(QQHelp.GetQQByUid(item.Cookie, match.Groups["uin"].Value, item.Vfwebqq), match.Groups["uin"].Value);
        //                        }

        //                        //获取对好友的备注信息
        //                        Regex marknames = new Regex("({\"uin\":)(?<uin>[0-9]{5,11}?)(,\"markname\":)(?<markname>.+?)(})");
        //                        foreach (Match match in marknames.Matches(html2))
        //                        {
        //                            if (friendList.Keys.Contains(match.Groups["uin"].Value))
        //                            {
        //                                friendList[match.Groups["uin"].Value] = match.Groups["markname"].Value;
        //                            }
        //                        }

        //                        //获取好友昵称
        //                        Regex info = new Regex("({\"face\":)(?<face>.+?)(,\"flag\":)(?<flag>.+?)(,\"nick\":\")(?<nick>.+?)(,\"uin\":)(?<uin>[0-9]{5,11}?)(})");
        //                        foreach (Match match in info.Matches(html2))
        //                        {
        //                            if (friendList.Keys.Contains(match.Groups["uin"].Value) && friendList[match.Groups["uin"].Value] == "")
        //                            {
        //                                friendList[match.Groups["uin"].Value] = match.Groups["nick"].Value;
        //                            }
        //                        }
        //                        item.friends = friendList;
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        MessageBox.Show("QQ好友信息获取失败," + ex.Message);
        //                    }

        //                    lvMain.Items[i].SubItems[5].Text = QQHelp.GetOnlineTimes(item.Cookie);//获取今日在线时长
        //                    lvMain.Tag = item;

        //                    ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
        //                    {
        //                        tssStatus2.Text = item.QQ + " 获取好友信息完毕...";
        //                    }));
                           
        //                }
        //                else
        //                {
        //                    if (msg.Contains("您输入的验证码有误"))
        //                    {
        //                        goto Retry;
        //                    }
        //                    lvMain.Items[i].SubItems[6].Text = msg;
        //                }
        //            }
        //        }
        //        start = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //    lvMain.Enabled = true;
        //}

        //登录选中
        private void tsmiLoginSelect_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(LoginSelect));
            thread.IsBackground = true;
            thread.Start();
        }

        private void LoginSelect()
        {
            try
            {
              
                    // item = lvMain.Items[0].Tag as QQData;

                Retry:
                    string cookie;
                    string verifycode = QQHelp.GetVerfyCode(item.QQ, out cookie);
                    if (verifycode == null)//跳过这条登录
                        return;
                    else
                    {
                        string ptwebqq, clientid, psessionid, vfwebqq;
                        ptwebqq = clientid = psessionid = vfwebqq = string.Empty;
                        string msg = string.Empty;
                        bool success = QQHelp.Login(item.QQ, item.Passwd, verifycode, item.ReadyStatus, ref cookie, ref ptwebqq, ref clientid, ref psessionid, ref vfwebqq, ref msg);
                        if (success)//登录成功
                        {
                            ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                            {
                                tssStatus2.Text = item.QQ + " 成功登录...";
                            }));
                            item.RefreshStart = DateTime.Now;
                            item.Status = item.ReadyStatus;
                            item.Cookie = cookie;
                            item.ClientId = clientid;
                            item.Ptwebqq = ptwebqq;
                            item.Psessionid = psessionid;
                            item.Vfwebqq = vfwebqq;
                            item.RefreshComplete = true;
                           // lvMain.Items[0].SubItems[2].Text = item.Status;
                            //lvMain.Items[0].SubItems[6].Text = msg;
                            LQQ.Text = item.QQ;
                            Lstaut.Text = item.Status;
                            //获取昵称
                            string url1 = "http://s.web2.qq.com/api/get_friend_info2?tuin=" + item.QQ + "&verifysession=&code=&vfwebqq=" + vfwebqq + "&t=" + DateTime.Now.ToFileTime();
                            string nickName = HttpHelp.GetHtml(url1, "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", ref cookie, Encoding.UTF8, false);
                            nickName = nickName.Remove(0, nickName.IndexOf("nick\":\"") + 7);
                            nickName = nickName.Substring(0, nickName.IndexOf("\","));
                           // lvMain.Items[0].SubItems[1].Text = nickName;
                            Lnick.Text = nickName;
                            ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                            {
                                tssStatus2.Text = item.QQ + " 获取等级信息...";
                            }));

                            try
                            {
                                //获取等级和剩余升级天数
                                string level, remainDays;
                                string url2 = "http://s.web2.qq.com/api/get_qq_level2?tuin=" + item.QQ + "&vfwebqq=" + vfwebqq + "&t=" + DateTime.Now.ToFileTime();
                                string html = HttpHelp.GetHtml(url2, "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", ref cookie, Encoding.UTF8, false);
                                html = html.Remove(0, html.IndexOf("level\":") + 7);
                                level = html.Substring(0, html.IndexOf(","));
                                html = html.Remove(0, html.IndexOf("remainDays\":") + 12);
                                remainDays = html.Substring(0, html.IndexOf(","));
                               // lvMain.Items[0].SubItems[3].Text = level;
                                //lvMain.Items[0].SubItems[4].Text = remainDays + "天";
                                Llevel.Text = level;
                                
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("QQ等级信息获取失败，" + ex.Message);
                            }

                            ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                            {
                                tssStatus2.Text = item.QQ + " 获取好友信息...";
                            }));

                            try
                            {
                                //获取好友列表
                                string postData = "r={\"h\":\"hello\",\"vfwebqq\":\"" + vfwebqq + "\"}";
                                WebHeaderCollection header;
                                string html2 = HttpHelp.GetHtml("http://s.web2.qq.com/api/get_user_friends2", "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", postData, ref cookie, true, out header, "application/x-www-form-urlencoded; charset=UTF-8", Encoding.UTF8, false);

                                friendList = new Dictionary<string, string>();//保存好友id值集合

                                Regex friend = new Regex("({\"flag\":)(?<flag>[0-9]{1,2}?)(,\"uin\":)(?<uin>[0-9]{5,11}?)(,\"categories\":)(?<id>[0-9]{1,2}?)(})");
                                foreach (Match match in friend.Matches(html2))
                                {
                                    string uid = match.Groups["uin"].Value;
                                    string qq = QQHelp.GetQQByUid(item.Cookie,uid, item.Vfwebqq);
                                   
                                    friendList.Add(qq, uid);
                                }
                                item.friends = friendList;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("QQ好友信息获取失败," + ex.Message);
                            }

                           // lvMain.Items[0].SubItems[5].Text = QQHelp.GetOnlineTimes(item.Cookie);//获取今日在线时长
                           // lvMain.Tag = item;
                            ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                            {
                                tssStatus2.Text = item.QQ + " 获取好友信息完毕...";
                            }));
                            panel1.Visible = true;
                            btnAdd.Text = "注销";
                           
                        }
                        else
                        {
                            if (msg.Contains("您输入的验证码有误"))
                            {
                                goto Retry;
                            }
                           // lvMain.Items[0].SubItems[6].Text = msg;
                        }
                    }
                
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //lvMain.Enabled = true;
           
        }
        //添加侦听
        void lin()
        {
            add();
        }
        void add()
        {
            if (!(listener != null && listener.IsListening))
            {
                listener = new HttpListener();
                listener.Prefixes.Add("http://*:9527/qq/"); //添加需要监听的url范围
                listener.Start(); //开始监听端口，接收客户端请求
                tssStatus.Text = "http端口侦听已经准备就绪";
                IAsyncResult result = listener.BeginGetContext(new AsyncCallback(EndGetRequest), listener);
                
            }
        }
        //
         void EndGetRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;
            HttpListener listener = (HttpListener)result.AsyncState;

            try
            {
                context = listener.EndGetContext(result);
                HandleRequest(context);
            }
            catch (Exception ex)
            {
                tssStatus2.Text = ex.Message;
            }
            finally
            {
                if (context != null)
                    context.Response.Close();

                if (listener.IsListening)
                    listener.BeginGetContext(EndGetRequest, listener);
            }
          
          


        }
        //
         void HandleRequest(HttpListenerContext context)
        {
           

            string responseStr = "0";
         
                
                if (item.Status.Contains("我在"))
                {

                    //string toqq = context.Request.QueryString["toqq"];
                    //string msg = context.Request.QueryString["msg"];
                    //string type = context.Request.QueryString["type"];
                    if (!context.Request.HasEntityBody)//无数据
                    {
                        context.Response.StatusCode = 403;
                        return;
                    }
                    string uid = "";
                    string toqq="";
                    string msg="";
                    string type="";
                    HttpListenerRequest request = context.Request;
                    
                    System.IO.Stream body = request.InputStream;
                    System.Text.Encoding encoding = Encoding.UTF8;
                    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
                    if (request.ContentType != null)
                    {
                        tssStatus2.Text= request.ContentType;
                    }
                    string code = reader.ReadToEnd();
                    
                    body.Close();
                    reader.Close();
                    string[] tmp = code.Split(new char[] { '&' });
                    foreach (string s in tmp)
                    {
                        string[] value=s.Split(new char[]{'='});
                        switch (value[0])
                        {
                            case "toqq":
                                toqq = value[1];
                                break;
                            case "msg":
                                msg = value[1];
                                break;
                            case "type":
                                type = value[1];
                                break;
                            default:
                                break;
                        }
                    }
                    

                    if (friendList != null&&toqq!=null)
                    {
                        if (friendList.ContainsKey(toqq))
                        {
                            uid = friendList[toqq].ToString();
                            bool result = QQHelp.SendMsg(item.Cookie, uid, msg + "————来自：" + type, item.ClientId, item.Psessionid);
                            if (result)
                                responseStr = "1";
                        }
                    }
                }

 
            byte[] response = System.Text.Encoding.Default.GetBytes(responseStr);
            context.Response.ContentType = "text/html"; //这里的类型随便你写.如果想返回HTML格式使用text/html
            context.Response.StatusCode = 200;
            context.Response.ContentLength64 = response.LongLength;
            context.Response.OutputStream.Write(response, 0, response.Length);
        }
       

        //停止侦听
        static void Stop()
        {
            if (!listener.IsListening)
                return;
            listener.Close();
            listener = null;
        }
       

        //断开选中
        private void tsmiOfflineSelect_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(OfflineSelect));
            thread.IsBackground = true;
            thread.Start();
        }

        private void OfflineSelect()
        {
            //lvMain.Enabled = false;
            panel1.Visible = false;

            if (!string.IsNullOrEmpty(item.Cookie) && !string.IsNullOrEmpty(item.ClientId) && !string.IsNullOrEmpty(item.Psessionid))
            {
                string msg = string.Empty;
                QQHelp.Logout(item.Cookie, item.ClientId, item.Psessionid, ref msg);


                QQData data = new QQData();
                data.QQ = item.QQ;
                data.Passwd = item.Passwd;
                data.ReadyStatus = item.ReadyStatus;
                ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                {
                    tssStatus2.Text = item.QQ + " 断开成功...";
                }));
                btnAdd.Text = "登录";
                panel2.Enabled = true;

            }
        }

        //删除选中QQ号码
       

        //开机自动运行
        private void chkRun_CheckedChanged(object sender, EventArgs e)
        {
            if (firstLoad == false)
            {
                try
                {
                    if (chkRun.Checked)
                    {
                        Run(true);
                        MessageBox.Show("设置开机启动成功！");
                    }
                    else
                    {
                        Run(false);
                        MessageBox.Show("取消开机启动成功！");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        //自动登录所有QQ号码
        private void chkAutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            if (firstLoad == false)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlPath);
                XmlNode autoLogin = doc.SelectSingleNode("/config/Settings/add[@key='AutoLogin']");
                if (autoLogin != null)
                    autoLogin.Attributes["value"].Value = chkAutoLogin.Checked.ToString();
                doc.Save(xmlPath);
            }
        }

       

        private void txtRefreshTime_Leave(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlPath);
            XmlNode refreshTime = doc.SelectSingleNode("/config/Settings/add[@key='RefreshTime']");
            if (refreshTime != null)
                refreshTime.Attributes["value"].Value = txtRefreshTime.Text;
            doc.Save(xmlPath);
        }

        private void txtRefreshTime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b'))
            {
                e.Handled = true;
            }
        }

        //设置程序开机是否自启动
        private void Run(bool flag)
        {
            string strName = Application.ExecutablePath;
            string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1, strName.LastIndexOf(".") - strName.LastIndexOf("\\") - 1);
            //指定文件是否存在
            if (!File.Exists(strName))
                return;
            Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (Rkey == null)
                Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
            //修改注册表
            if (flag)
                Rkey.SetValue(strnewName, strName);//设置开机启动
            else
                Rkey.DeleteValue(strnewName);//取消开机启动
        }

        private void txtQQNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b'))
            {
                e.Handled = true;
            }
        }
       

        //创建桌面快捷方式
        private void chCreateDesktopLnk_CheckedChanged(object sender, EventArgs e)
        {
            if (firstLoad == false)
            {
                string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);//得到桌面文件夹
                if (chCreateDesktopLnk.Checked)
                {
                    string target = Application.StartupPath + @"\WebQQ批量挂QQ.exe";
                    IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();

                    IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(DesktopPath + "\\WebQQ3.0批量挂QQ.lnk");
                    shortcut.TargetPath = target;
                    shortcut.Arguments = "";// 参数
                    shortcut.Description = "WEBQQ3.0批量挂qq软件";
                    shortcut.WorkingDirectory = Application.StartupPath;//程序所在文件夹，在快捷方式图标点击右键可以看到此属性
                    shortcut.IconLocation = target + ",0";//图标
                    shortcut.Hotkey = "CTRL+SHIFT+Z";//热键
                    shortcut.WindowStyle = 1;
                    shortcut.Save();
                }
                else
                {
                    if (File.Exists(DesktopPath + "\\WebQQ3.0批量挂QQ.lnk"))
                    {
                        File.Delete(DesktopPath + "\\WebQQ3.0批量挂QQ.lnk");
                    }
                }
                MessageBox.Show("操作完成！");
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
                if (!string.IsNullOrEmpty(item.Psessionid) && !string.IsNullOrEmpty(item.ClientId))
                {
                    TimeSpan ts = DateTime.Now - item.RefreshStart;
                    if (ts.TotalSeconds >= int.Parse(txtRefreshTime.Text.Trim()) && item.RefreshComplete == true)//session刷新间隔
                    {
                        //if (item.Status != "离线")
                        //    lvMain.Items[i].SubItems[5].Text = QQHelper.GetOnlineTimes(item.Cookie);
                        item.Index = 0;
                        item.RefreshStart = DateTime.Now;
                        item.RefreshComplete = false;
                        Thread thread = new Thread(new ParameterizedThreadStart(RefreshSession));
                        thread.IsBackground = true;
                        thread.Start(item);
                    }
                }
            
        }

        //通过定时检测是否有qq消息返回，刷新session，保持在线
        private void RefreshSession(object obj)
        {
            //获取好友列表
            QQData item = obj as QQData;
            string postData = "r={\"h\":\"hello\",\"vfwebqq\":\"" + item.Vfwebqq + "\"}";
            WebHeaderCollection header;
           
            ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
            {
                tssStatus2.Text = item.QQ + " 开始获取QQ消息...";
            }));
            string cookie = item.Cookie;

            string url = "http://d.web2.qq.com/channel/poll2?key=0&clientid=" + item.ClientId + "&psessionid=" + item.Psessionid + "&t=" + DateTime.Now.ToFileTime();
            string html = GetHtml(url, "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2", ref cookie, Encoding.UTF8, false);

            if (html.Contains(@"\u60A8\u7684\u8D26\u53F7\u5728\u53E6\u4E00\u5730\u70B9\u767B\u5F55\uFF0C\u60A8\u5DF2\u88AB\u8FEB\u4E0B\u7EBF\u3002\u5982\u6709\u7591\u95EE\uFF0C\u8BF7\u767B\u5F55"))
            {
                
               Lstaut.Text = "QQ在另一个地方登录,您被迫下线";
                QQData data = new QQData();
                data.QQ = item.QQ;
                data.Passwd = item.Passwd;
                data.ReadyStatus = item.ReadyStatus;
                data.RefreshComplete = true;
                item= data;

                ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                {
                    tssStatus2.Text = item.QQ + " QQ在另一个地方登录,您被迫下线...";
                }));
            }
               else
                if (html.Contains("poll_type\":\"system_message"))//添加好友
                {
                    string html2 = HttpHelp.GetHtml("http://s.web2.qq.com/api/get_user_friends2", "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2", postData, ref cookie, true, out header, "application/x-www-form-urlencoded; charset=UTF-8", Encoding.UTF8, false);

                    friendList = new Dictionary<string, string>();//保存好友id值集合

                    Regex friend = new Regex("({\"flag\":)(?<flag>[0-9]{1,2}?)(,\"uin\":)(?<uin>[0-9]{5,11}?)(,\"categories\":)(?<id>[0-9]{1,2}?)(})");
                    foreach (Match match in friend.Matches(html2))
                    {
                        string uid = match.Groups["uin"].Value;
                        string qq = QQHelp.GetQQByUid(item.Cookie, uid, item.Vfwebqq);

                        friendList.Add(qq, uid);
                    }
                }
            else if (html.Contains("poll_type\":\"message"))
            {
                ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
                {
                    tssStatus2.Text = item.QQ + " 收到消息...";
                }));

                string from_uin = "", to_uin = "", content = "";

                html = html.Remove(0, html.IndexOf("from_uin\":") + 10);
                from_uin = html.Substring(0, html.IndexOf(",\"to_uin"));

                html = html.Remove(0, html.IndexOf("to_uin\":") + 8);
                to_uin = html.Substring(0, html.IndexOf(",\"msg_id2"));

                html = html.Remove(0, html.IndexOf("\"name\":"));
                html = html.Remove(0, html.IndexOf(",\"") + 2);
                content = HttpHelp.ConvertUnicodeStringToChinese(html.Substring(0, html.IndexOf("\"]")));

                string fromQQ = QQHelp.GetQQByUid(item.Cookie, from_uin, item.Vfwebqq);//获取真实qq号码
                //如果有备注显示备注名称，没有备注显示昵称
                string nickname = "";
                if (item.friends.ContainsKey(from_uin))
                    nickname = item.friends[from_uin];
                bool add = true;
                for (int i = 0; i < lvChat.Items.Count; i++)
                {
                    if (lvChat.Items[i].Text == fromQQ && lvChat.Items[i].SubItems[1].Text == to_uin)
                    {
                        add = false;
                        break;
                    }
                }
                //原来有这个人发送消息则不添加新项
                if (add)
                {
                    ListViewItem lvItem = lvChat.Items.Add(lvChat.Items.Count.ToString(), fromQQ, 0);
                    lvItem.SubItems.Add(to_uin);
                    lvItem.SubItems.Add(from_uin);
                    lvItem.Tag = item;
                }
                rtxtChat.AppendText(nickname.Trim(new char[] { '"' }) + "(" + fromQQ + ")对" + to_uin + "说:\r\n" + DateTime.Now.ToLongTimeString() + "\r\n" + content.Replace("\\r", "\r\n") + "\r\n");
                rtxtChat.ScrollToCaret();
                //播放消息提示文件
                //SoundPlayer sp = new SoundPlayer("msg.wav");
                //sp.Play();
            }
            item.RefreshComplete = true;//刷新消息完毕
           

            ControlCrossThreadCalls.SafeInvoke(this, new ControlCrossThreadCalls.InvokeHandler(delegate()
            {
                tssStatus2.Text = item.QQ + " 获取QQ消息结束...";
            }));
            Common.ClearMemory();
        }

        public static string GetHtml(string url, string referer, ref string cookie, Encoding encoding, bool getResponseCookie)
        {
            string html = string.Empty;
            HttpWebRequest webRequest = null;
            HttpWebResponse response = null;
            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webRequest.Headers[HttpRequestHeader.Cookie] = cookie;
                webRequest.Referer = referer;
                webRequest.KeepAlive = false;
                webRequest.Timeout = 15000;//超时时间
                webRequest.Method = "GET";
                webRequest.ContentType = "utf-8";
                webRequest.Headers.Set("Accept-Language", "zh-cn,zh;q=0.5");
                webRequest.Headers.Set("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
                webRequest.Headers.Set("Cache-Control", "no-cache");
                webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";

                response = (HttpWebResponse)webRequest.GetResponse();
                using (Stream getStream = response.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(getStream, encoding))
                    {
                        html = streamReader.ReadToEnd();
                    }
                }
                if (getResponseCookie)
                    cookie = response.Headers[HttpResponseHeader.SetCookie];
            }
            catch (WebException)
            {
                html = "";
            }
            catch (Exception)
            {
                html = "";
            }
            finally
            {
                if (webRequest != null)
                    webRequest.Abort();
                if (response != null)
                    response.Close();
            }
            return html;
        }

        //发送聊天消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (lvChat.SelectedItems.Count > 0)
            {
                if (rtxtSendMessage.Text == "")
                    rtxtSendMessage.Text = "...";
                string str = lvChat.SelectedItems[0].Tag.ToString();
                string toQQ = lvChat.SelectedItems[0].SubItems[2].Text;
                QQData item = lvChat.SelectedItems[0].Tag as QQData;
                bool result = QQHelp.SendMsg(item.Cookie, toQQ, rtxtSendMessage.Text, item.ClientId, item.Psessionid);
                if (result)
                {
                    rtxtChat.AppendText(lvChat.SelectedItems[0].SubItems[1].Text + "对" + toQQ + "说:\r\n" + DateTime.Now.ToLongTimeString() + "\r\n" + rtxtSendMessage.Text + "\r\n");
                    rtxtChat.ScrollToCaret();
                    rtxtSendMessage.Text = "";
                }
                else
                {
                    rtxtChat.Text += "消息发送失败！发送频率过快或QQ掉线或网络掉线！\r\n";
                }
            }
            else
            {
                MessageBox.Show("请选择要回复的消息！");
                lvChat.Focus();
            }
        }

        //清空聊天信息
        private void btnClear_Click(object sender, EventArgs e)
        {
            rtxtChat.Text = string.Empty;
        }

        private void rtxtSendMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                btnSend.PerformClick();//ctrl+enter发送消息
            }
        }

        //保存聊天消息
        private void tsmiSaveChatMessage_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.Write(rtxtChat.Text.Replace("\n", "\r\n"));
                    }
                }
            }
        }

      
     

       

        //截获系统关机消息
        private bool isExitApp = false;
        private const int WM_QUERYENDSESSION = 0x0011;
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_QUERYENDSESSION:
                    isExitApp = true;
                    Application.Exit();
                    base.WndProc(ref m);
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }

        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            isExitApp = true;
            Application.Exit();
            Close();
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            notifyIcon1.Dispose();
            Close();
            
            //System.Environment.Exit(System.Environment.ExitCode);
            this.Dispose();
            this.Close();
         
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!this.isExitApp)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(OfflineSelect));
            thread.IsBackground = true;
            thread.Start();
        }

    }
}
